<template>
  <n-modal v-model:show="showModal">
    <n-card style="width: 800px" title="创建视频流分析任务" :bordered="false">
      <n-steps :current="currentStep" class="mb-4">
        <n-step title="选择任务模式" />
        <n-step title="创建任务" />
        <n-step title="设置摄像头和选择算法" />
      </n-steps>

      <!-- 第一步：选择任务模式 -->
      <div v-if="currentStep === 1">
        <n-space vertical>
          <n-button
            type="primary"
            block
            @click="handleSelectMode('realtime')"
            :type="selectedMode === 'realtime' ? 'primary' : 'tertiary'"
            :ghost="selectedMode !== 'realtime'"
          >
            实时任务
          </n-button>
          <n-button
            type="info"
            block
            @click="handleSelectMode('polling')"
            :type="selectedMode === 'polling' ? 'info' : 'tertiary'"
            :ghost="selectedMode !== 'polling'"
          >
            轮询任务
          </n-button>
        </n-space>

        <!-- 添加提示信息 -->
        <n-alert v-if="!selectedMode" type="warning" class="mt-4"> 请选择任务模式 </n-alert>
      </div>

      <!-- 第二步：创建任务 -->
      <div v-if="currentStep === 2">
        <n-form :model="taskForm" label-placement="left" label-width="auto">
          <n-form-item label="任务名称">
            <n-input v-model:value="taskForm.name" />
          </n-form-item>
          <n-form-item label="任务描述">
            <n-input
              v-model:value="taskForm.description"
              type="textarea"
              :autosize="{ minRows: 3 }"
            />
          </n-form-item>
          <!-- 更多任务字段 -->
        </n-form>
      </div>
      <!-- 第三步：设置摄像头和选择算法 -->
      <div v-if="currentStep === 3">
        <n-form :model="taskForm" label-placement="left" label-width="auto">
          <n-form-item label="摄像头选择">
            <n-select
              v-model:value="taskForm.device_id"
              :options="deviceOptions"
              placeholder="请选择摄像头"
              :loading="deviceLoading"
              :remote="true"
              @focus="handleDeviceFocus"
            />
          </n-form-item>
          <n-form-item label="算法选择">
            <n-select
              v-model:value="taskForm.algorithm_ids"
              :options="algorithmOptions"
              placeholder="请选择分析算法"
              multiple
              :max-tag-count="2"
              :render-tag="renderTag"
              filterable
              :loading="algorithmLoading"
              :remote="true"
              @focus="handleAlgorithmFocus"
            />
          </n-form-item>
        </n-form>
      </div>

      <!-- 操作按钮 -->
      <div class="mt-4 text-right">
        <n-button v-if="currentStep === 2" type="default" class="mr-2" @click="currentStep--">
          上一步
        </n-button>
        <n-button
          type="primary"
          :disabled="currentStep === 1 && !selectedMode"
          @click="handleNextStep"
        >
          {{ currentStep != 3 ? '下一步' : '创建任务' }}
        </n-button>
      </div>
    </n-card>
  </n-modal>
</template>

<script lang="ts" setup>
  import { ref, reactive, getCurrentInstance, h } from 'vue';
  import {
    NModal,
    NCard,
    NButton,
    NSteps,
    NStep,
    NSpace,
    NForm,
    NFormItem,
    NInput,
    NSelect,
    useMessage,
    NTag,
  } from 'naive-ui';

  import { CreateTask, FetchAlgorithmList, FetchDeviceList } from '@/api/analysis/task';

  const deviceOptions = ref<Array<{ label: string; value: number }>>([]);
  const algorithmOptions = ref<Array<{ label: string; value: number }>>([]);

  const message = useMessage();
  const showModal = ref(false);
  const currentStep = ref(1); // 当前步骤
  const selectedMode = ref<'realtime' | 'polling' | ''>(''); // 选中的任务模式
  const loading = ref(false);
  // 添加loading状态
  const deviceLoading = ref(false);
  const algorithmLoading = ref(false);

  // 任务表单数据
  const taskForm = reactive({
    name: '',
    description: '',
    device_id: '',
    rtsp_url: '',
    algorithm_ids: [] as number[], // 改为数组类型
  });

  // 添加自定义标签渲染
  const renderTag = ({ option, handleClose }: { option: any; handleClose: () => void }) => {
    return h(
      NTag,
      {
        type: 'info',
        closable: true,
        onClose: (e: MouseEvent) => {
          e.stopPropagation();
          handleClose();
        },
      },
      option.label
    );
  };

  // 打开弹窗
  function open() {
    showModal.value = true;
    currentStep.value = 1; // 重置为第一步
    selectedMode.value = ''; // 重置选中的模式
  }

  // 关闭弹窗
  function close() {
    showModal.value = false;
  }

  // 处理选择任务模式
  function handleSelectMode(mode: 'realtime' | 'polling') {
    selectedMode.value = mode;
    message.success(`已选择：${mode === 'realtime' ? '实时任务' : '轮询任务'}`);
  }

  // 添加处理函数
  async function handleDeviceFocus() {
    if (deviceOptions.value.length === 0 && !deviceLoading.value) {
      deviceLoading.value = true;
      try {
        deviceOptions.value = await fetchDeviceList();
      } catch (error) {
        message.error('获取设备列表失败');
      } finally {
        deviceLoading.value = false;
      }
    }
  }

  async function handleAlgorithmFocus() {
    if (algorithmOptions.value.length === 0 && !algorithmLoading.value) {
      algorithmLoading.value = true;
      try {
        algorithmOptions.value = await fetchAlgorithmList();
      } catch (error) {
        message.error('获取算法列表失败');
      } finally {
        algorithmLoading.value = false;
      }
    }
  }

  async function fetchDeviceList() {
    try {
      const response = await FetchDeviceList();
      return response.map((device) => ({
        label: device.name,
        value: device.id,
      }));
    } catch (error) {
      message.error('获取算法列表失败');
      return [];
    }
  }

  async function fetchAlgorithmList() {
    try {
      const response = await FetchAlgorithmList();
      return response.map((algorithm) => ({
        label: algorithm.chineseName,
        value: algorithm.id,
      }));
    } catch (error) {
      message.error('获取算法列表失败');
      return [];
    }
  }
  // 处理下一步或创建任务
  function handleNextStep() {
    if (currentStep.value === 1) {
      if (!selectedMode.value) {
        message.warning('请先选择任务模式');
        return;
      }
      currentStep.value++;
    } else if (currentStep.value === 2) {
      if (!taskForm.name) {
        message.warning('请输入任务名称');
        return;
      }
      currentStep.value++;
    } else {
      try {
        loading.value = true;

        // 确保至少选择了一个算法
        if (!taskForm.device_id) {
          message.warning('请至少选择一个设备');
          return;
        }

        // 确保至少选择了一个算法
        if (taskForm.algorithm_ids.length === 0) {
          message.warning('请至少选择一个算法');
          return;
        }

        const resp = CreateTask({
          name: taskForm.name,
          description: taskForm.description,
          task_mode: selectedMode.value,
          device_id: taskForm.device_id,
          rtsp_url: taskForm.rtsp_url,
          algorithm_ids: taskForm.algorithm_ids,
          status: 0,
          // 默认创建时状态为0(停用)
        });

        if (resp && resp.id) {
          // 检查响应是否包含任务ID
          message.success(`任务创建成功，ID: ${resp.id}`);
          close();
          // 触发父组件刷新任务列表
          const instance = getCurrentInstance();
          instance?.parent?.exposed?.getTaskList?.();
        } else {
          message.error('创建任务失败: 响应数据异常');
        }
      } catch (error) {
        message.error(`创建任务失败: ${error || '未知错误'}`);
      } finally {
        loading.value = false;
      }
      return;
    }
  }

  // 暴露方法
  defineExpose({ open, close });
</script>
